package cn.interestingshop.web.manager;

import cn.interestingshop.entity.Classify;
import cn.interestingshop.entity.Goods;
import cn.interestingshop.service.classify.ClassifyService;
import cn.interestingshop.service.classify.ClassifyServiceImpl;
import cn.interestingshop.service.goods.GoodsService;
import cn.interestingshop.service.goods.GoodsServiceImpl;
import cn.interestingshop.utils.EmptyUtils;
import cn.interestingshop.utils.JedisUtil;
import cn.interestingshop.utils.Pager;
import cn.interestingshop.web.AbstractServlet;
import com.alibaba.fastjson.JSONObject;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;


@WebServlet(name = "Goods2Servlet", urlPatterns = "/manager/goods")
public class GoodsServlet extends AbstractServlet {
    @Override
    public Class getServletClass() {
        return GoodsServlet.class;
    }

    public String index(HttpServletRequest request, HttpServletResponse response) {

        String currentPage = request.getParameter("currentPage");
        int currentPageNo = EmptyUtils.isEmpty(currentPage) ? 1 : Integer.valueOf(currentPage);


        GoodsService goodsService = new GoodsServiceImpl();

        List<Goods> goods = goodsService.selectAll(currentPageNo, 8);


        int count = goodsService.findUserCount();

        Pager pager = new Pager(count, 8, currentPageNo);
        pager.setUrl("manager/goods?action=index");

        request.setAttribute("goodsList", goods);
        request.setAttribute("pager", pager);

        return "goods/goodsList";
    }

    public void deleteById(HttpServletRequest request, HttpServletResponse response) {
        GoodsService goodsService = new GoodsServiceImpl();

        int id = goodsService.deleteById(Integer.parseInt(request.getParameter("id")));

        JSONObject jsonObject = new JSONObject();

        if (id > 0) {
            jsonObject.put("status", 1);
            JedisUtil.getJedis().del("classifyVoList");
            JedisUtil.getJedis().del("notice");

        } else {
            jsonObject.put("status", 0);
            jsonObject.put("message", "删除失败");
        }

        try {
            response.getWriter().print(jsonObject);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String toUpdategoods(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("id"));

        GoodsService goodsService = new GoodsServiceImpl();

        Goods goods = goodsService.selectOne(id);

        ClassifyService classifyService = new ClassifyServiceImpl();

        List<Classify> classifyList1 = classifyService.selectOneType(1);
        List<Classify> classifyList2 = classifyService.selectOneType(2);
        List<Classify> classifyList3 = classifyService.selectOneType(3);

        request.setAttribute("goods", goods);
        request.setAttribute("classifyList1", classifyList1);
        request.setAttribute("classifyList2", classifyList2);
        request.setAttribute("classifyList3", classifyList3);

        return "/manager/goods/toAddGoods";
    }

    public void addGoods(HttpServletRequest request, HttpServletResponse response) {


        String fileName = "";
        Goods goods=new Goods();
        boolean ok=false;


        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            //将上传内容封装为FileItem
            List<FileItem> fileItems = upload.parseRequest(request);
            System.out.println(fileItems);
            for (FileItem item : fileItems) {

                if (item.getName() != null && item.getName()!="") {
                    //上传文件的inputstream
                    InputStream inputStream = item.getInputStream();
                    //上传文件本身的名字
                    fileName = item.getName();
                    //获取新建的uploadfiles文件夹的实际路径
                    //根据之前的设定，这个路径是: 项目文件夹/src/main/webapp/uploadfiles
                    String path = getServletContext().getRealPath("\\files");
                    System.out.println("服务器保存文件路径是: " + path + "\\" + fileName);
                    //利用FileOutputStream将内容保存到服务器上
                    FileOutputStream outputStream = new FileOutputStream(new File(path + "\\" + fileName));
                    byte[] bytes = new byte[1024];
                    int count = 0;
                    while ((count = inputStream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, count);
                    }
                    inputStream.close();
                    outputStream.close();
                    //重定向到jsp文件，并将刚刚上传文件的路径作为img参数的值
                }else{

                    String name = item.getFieldName();
                    String value = item.getString("UTF-8");
                    if(name.equals("classifyLevel1Id")){
                        goods.setClassifyLevel1Id(Integer.parseInt(value));
                    }
                    if(name.equals("classifyLevel2Id")){
                        goods.setClassifyLevel2Id(Integer.parseInt(value));
                    }
                    if(name.equals("classifyLevel3Id")){
                        goods.setClassifyLevel3Id(Integer.parseInt(value));
                    }
                    if(name.equals("goodsName")){
                        goods.setGoodsName(value);
                    }
                    if(name.equals("goodsDesc")){
                        goods.setGoodsDesc(value);
                    }
                    if(name.equals("price")){
                        goods.setPrice(Float.parseFloat(value));
                    }
                    if(name.equals("stock")){
                        goods.setStock(Integer.parseInt(value));
                    }


                    if(name.equals("id")){
                        if(!value.equals("") && value!=null){
                            goods.setId(Integer.parseInt(value));
                            ok=true;
                        }

                    }





                    System.out.println(name + "=" + value);


                }
            }
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            e.printStackTrace();
        }











        GoodsService goodsServices=new GoodsServiceImpl();

        goods.setFileName(fileName);



        if (ok==true) {
            int rs=goodsServices.executeUpdate(goods);
        }else{
            int rs=goodsServices.insert(goods);
        }

        JedisUtil.getJedis().del("classifyVoList");
        JedisUtil.getJedis().del("notice");

        try {
            response.sendRedirect("goods?action=index");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public String toAddGoods(HttpServletRequest request,HttpServletResponse response){
        ClassifyService classifyService = new ClassifyServiceImpl();

        List<Classify> classifyList1 = classifyService.selectOneType(1);
        List<Classify> classifyList2 = classifyService.selectOneType(2);
        List<Classify> classifyList3 = classifyService.selectOneType(3);

        request.setAttribute("classifyList1", classifyList1);
        request.setAttribute("classifyList2", classifyList2);
        request.setAttribute("classifyList3", classifyList3);
        return "/manager/goods/toAddGoods";
    }


}
